package cn.ywang.register;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 注册式单例
 * Spring中使用的就是注册式单例
 *
 * @Auther: BeatificWang
 * @Date: 2018/9/23 21:09
 */
public class BeanFactory {
	private BeanFactory() {
	}

	// 线程安全
	private static Map<String, Object> ioc = new ConcurrentHashMap<>();

	public static Object getBean(String className) {
		synchronized (ioc) {
			if (!ioc.containsKey(className)) {
				Object object = null;
				try {
					object = Class.forName(className).newInstance();
					ioc.put(className, object);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return object;
			}
			else {
				return ioc.get(className);
			}
		}
	}

}
